package com.jamlu.framework.ui.status;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jamlu.framework.R;
import com.jamlu.framework.utils.ToastPts;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;


/**
 * 进入这个布局，肯定有数据了，而且状态布局消失了，这个针对SmartRefreshLayout和RecyclerView
 * 这个布局初始化后不允许随意remove，因为在addOnAttachStateChangeListener中监听离开就释放所有资源
 * Created by DMing on 2017/2/26 0026.
 */
public class StatusSmartRvView implements IStatus {

    private RecyclerView mRvData;//数据表
    private SmartRefreshLayout mRefreshLayout;//刷新控件

    private List dataList = new ArrayList<>(); //主页数据列表
    private int contentSize = 15; //每次请求条目最大数目
    private int index; //当前数据列表索引

    private StatusRequest statusRequest; //请求run
    private CompositeDisposable mCompositeDisposable; //disposable池
    private Disposable mDisposable;//取消

    StatusSmartRvView(ViewGroup rootView) {
        View layoutStatus = LayoutInflater.from(rootView.getContext()).inflate(R.layout.layout_refresh,rootView,false);
        mRefreshLayout = layoutStatus.findViewById(R.id.sl_refresh);
        mRvData = layoutStatus.findViewById(R.id.rv_data);
        rootView.addView(layoutStatus);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(rootView.getContext()));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(rootView.getContext()));
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getHttpData(true);
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getHttpData(false);
            }
        });
        mRvData.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {

            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                releaseRef();
            }
        });
    }

    @SuppressWarnings("unchecked")
    void initEvent(ViewGroup rootView, BaseQuickAdapter baseQuickAdapter, CompositeDisposable mCompositeDisposable, StatusRequest statusRequest){
        this.mCompositeDisposable = mCompositeDisposable;
        this.statusRequest = statusRequest;
        mRvData.setLayoutManager(new LinearLayoutManager(rootView.getContext()));
        mRvData.setAdapter(baseQuickAdapter);
        baseQuickAdapter.setNewData(dataList);
    }

    /**
     * 获取数据List
     * @return 数据List
     */
    @SuppressWarnings("unused")
    public List getDataList(){
        return dataList;
    }

    /**
     * 获取RecyclerView
     * @return 获取RecyclerView
     */
    @SuppressWarnings("unused")
    public RecyclerView getRvView(){
        return mRvData;
    }

    /**
     * 获取BaseQuickAdapter
     * @return BaseQuickAdapter
     */
    @SuppressWarnings("unused")
    public BaseQuickAdapter getBaseQuickAdapter(){
        return (BaseQuickAdapter) mRvData.getAdapter();
    }

    /**
     * 获取刷新layout
     * @return SmartRefreshLayout
     */
    @SuppressWarnings("unused")
    public SmartRefreshLayout getSmartRefreshLayout(){
        return mRefreshLayout;
    }

    /**
     * 获取当前请求的index
     * @return index
     */
    @SuppressWarnings("unused")
    public int getIndex(){
        return index;
    }

    /**
     * 获取每页大小
     * @return 每页大小
     */
    @SuppressWarnings("unused")
    public int getContentSize() {
        return contentSize;
    }

    /**
     * 设置每页大小
     * @param contentSize 每页大小
     */
    @SuppressWarnings("unused")
    public void setContentSize(int contentSize) {
        this.contentSize = contentSize;
    }

    /**
     * 结束刷新，完结,没有数据了
     */
    private void finishLoadMore(){
        completeRefresh(true);
        mRefreshLayout.finishLoadmoreWithNoMoreData();
    }

    /**
     * 完成刷新，还未完结
     * @param success 是否成功
     */
    private void completeRefresh(boolean success){
        mRefreshLayout.finishRefresh(success);
        mRefreshLayout.finishLoadmore(success);
    }


    /**
     * 请求数据成功
     * @param list 数据
     */
    @SuppressWarnings("unchecked")
    private void onHttpListSuccess(List list) {
        if (list.size() > 0) {
            if (index == 0)dataList.clear();
            dataList.addAll(list);
            mRvData.getAdapter().notifyDataSetChanged();
            if (list.size() == contentSize){
                index++;
                completeRefresh(true);
            }else {
                finishLoadMore();//数据不够请求的数量，即是没有数据了
            }
        }else {
            finishLoadMore();//没有数据了
        }
    }

    /**
     * 请求列表失败
     */
    private void onHttpListFailure() {
        completeRefresh(false);
    }


    /**
     *
     * @param clearData 是否清除数据
     */
    private void getHttpData(boolean clearData){
        if (clearData) {
            index = 0;
        }
        ///////////////添加能取消Disposable
        if (mDisposable != null)mCompositeDisposable.remove(mDisposable);
        mDisposable = statusRequest.run(this); //这个肯定是新的
        mCompositeDisposable.add(mDisposable);
    }

    /**
     *
     * @param status 状态
     * @param obj 可选传入参数，可能为空
     */
    @SuppressWarnings("unchecked")
    @Override
    public void switchStatus(int status, Object... obj) {
        switch (status){
            case SUCCESS:
            case NOTHING:
                if (obj != null && obj.length == 1){
                    List list = (List) obj[0];
                    onHttpListSuccess(list);
                }
                break;
            case ERROR_RESPOND:
                onHttpListFailure();
                if (obj != null && obj.length == 1) {
                    ToastPts.show(String.format("%s%s", mRvData.getContext().getString(R.string.retry), obj[0]));
                }
                break;
            case ERROR_NETWORK:
                onHttpListFailure();
                ToastPts.show(mRvData.getContext().getString(R.string.status_error));
                break;
            case NO_NETWORK:
                onHttpListFailure();
                ToastPts.show(mRvData.getContext().getString(R.string.status_no_net));
                break;
            case LOADING:
                break;
        }
    }

    /**
     * 使用完结的时候调用
     */
    @Override
    public void releaseRef() {
        if (mDisposable != null && mCompositeDisposable != null)mCompositeDisposable.remove(mDisposable);
        dataList.clear();
        dataList = null;
        mRvData = null;
        mRefreshLayout = null;
        statusRequest = null;
        mCompositeDisposable = null;
        mDisposable = null;
    }
}
